package cn.itcast.core;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取当前类的字节码文件
            Class clazz = this.getClass();
            //获取uri
            String uri = request.getRequestURI();
            //切割出要访问的方法
            String page = uri.substring(uri.lastIndexOf("/")+1);
            //反射
            Method declaredMethod = clazz.getDeclaredMethod(page, HttpServletRequest.class, HttpServletResponse.class);
            //暴力
            declaredMethod.setAccessible(true);
            //访问该方法
            Object result = declaredMethod.invoke(this, request, response);
            //判断是否由ResponseAnnotation注解
            if(declaredMethod.getDeclaredAnnotation(ResponseAnnotation.class)!=null){
                response.setContentType("text/json;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                String s = objectMapper.writeValueAsString(result);
                response.getWriter().print(s);
                return;
            }
            //判断是否为空
            if(result!=null){
                if(result instanceof String){
                    String method = (String)result;
                    if(method.startsWith("forward:")){//转发
                        request.getRequestDispatcher("/"+method.substring(8)).forward(request,response);
                    }else if(method.startsWith("redirect:")){
                        response.sendRedirect(super.getServletContext().getContextPath()+"/"+method.substring(9));
                    }else {//默认转发
                        request.getRequestDispatcher("/"+method).forward(request,response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
